#include "game.h"
#include "ui_game.h"
#include "qobject.h"


Game::Game(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Game)
{


    ui->setupUi(this);

    timer.start(30);//计时器开始
    connect(&timer,SIGNAL(timeout()),this,SLOT(timeout_slot()));
    time.setHMS(0,0,0,0);
    ui->label->setText("寄时器");


    for(int i=0;i<8;i++)
    {
        cd[i] = new Card(this);
        connect(cd[i],&Card::sendSelf,this,&Game::getObject);
        cd[i]->move(QRandomGenerator::global()->bounded(500.00),QRandomGenerator::global()->bounded(500.00));
    }


}

Game::~Game()
{
    delete ui;
}


//获取坐标
void Game::getObject(Card *w)
{
    temp = w;
    startP = cursor().pos()-this->pos();
    yuanP = temp->pos();
    temp->raise();
}



void Game::timeout_slot()
{
    time=time.addMSecs(30);
    ui->label->setText(time.toString("hh:mm:ss:zzz"));
}



//卡牌控件的移动
void Game::mouseMoveEvent(QMouseEvent *event)
{
    temp->move(yuanP.x()+event->x()-startP.x(),yuanP.y()+event->y()-startP.y());
}



void Game::mouseReleaseEvent(QMouseEvent *event)
{
    temp->raise();
}


//绘制背景
void Game::paintEvent(QPaintEvent *ev)
{
    static int pos=0;
    QString pictures[2]={":/res/tabletop.png",""};
    QPainter *painter =new QPainter(this);
    QPixmap pixmap;
    pixmap.load(pictures[pos]);
    pixmap.scaled(512,512);
    painter->drawPixmap(0,0,512,512,pixmap);
    painter->end();
}



void Game::on_pushButton_clicked()
{
    timer.stop();
    Sleep(1000);
    time.setHMS(0,0,0,0);
    ui->label->setText("00:00:00:000");

    this->close();

    Game *d=new Game;
    d->show();
}



void Game::Sleep(int msec)
{
    QTime dieTime = QTime::currentTime().addMSecs(msec);
    while( QTime::currentTime() < dieTime )
    {
        QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
    }
}
